package com.arrogames.rgblabyrinth.animations {
	import com.greensock.TimelineMax;
	import com.greensock.TweenLite;
	
	import feathers.controls.LayoutGroup;
	
	import starling.display.DisplayObject;

	public class OptionsAnimationBuilder {
		
		private var parent:LayoutGroup;
		
		private var hideShowDuration:Number = 0.3;
		private var showTween:TimelineMax;
		private var hideTween:TimelineMax;
		
		private var iconSize:int;
		private var gap:int;
		private var visibleButtons:uint = 0;
		
		public function OptionsAnimationBuilder(parent:LayoutGroup, iconSize:int=24, gap:int=5) {
			this.parent = parent;
			this.iconSize = iconSize;
			this.gap = gap;
			this.visibleButtons = 2;
			reset();
		}
		
		public function showButtons(targets:Array):void {
			var child:DisplayObject;
			for (var i:int = 0; i < parent.numChildren; i++) {
				child = parent.getChildAt(i) as DisplayObject;
				if (targets.indexOf(child) > -1) {
					showButton(child);
				} else {
					hideButton(child);
				}
			}
			
			//reorder them.
			for (var j:int = 0; j < targets.length; j++) {
				parent.addChildAt(targets[j], j);
			}
			
			visibleButtons = targets.length;
		}
		
		private function showButton(target:DisplayObject):void {
			if (target.alpha != 1) {
				target.visible = true;
				showTween.add(TweenLite.to(target, hideShowDuration, {alpha:1}), 0);
			}
		}
		
		private function hideButton(target:DisplayObject):void {
			if (target.alpha != 0) {
				hideTween.add(TweenLite.to(target, hideShowDuration, {alpha:0, onComplete:doRemove, onCompleteParams:[target]}), 0);
			}
		}
		
		protected function doRemove(target:DisplayObject):void {
			target.visible = false;
		}

		public function create():TimelineMax {
			var result:TimelineMax = new TimelineMax();
			result.append(hideTween);
			result.append(showTween);
			var newX:int = (800 - parent.width) + (parent.width - ( (visibleButtons+1) * ( iconSize + gap ) ) );
			result.add(TweenLite.to(parent, 0.5, {x:newX}), 0);
			reset();
			return result;
		}
		
		private function reset():void {
			showTween = new TimelineMax();
			hideTween = new TimelineMax();
		}
	}
}